<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <div>
        <el-input size="medium" @keyup.enter.native="" placeholder="工作流名称" v-model="query.name"
                  style="width: 250px;" clearable></el-input>
        <el-input size="medium" @keyup.enter.native="" placeholder="执行用户" v-model="query.userName"
                  style="width: 200px;" clearable></el-input>
          <el-select size="medium" clearable v-model="query.state" placeholder="状态">
            <el-option v-for="item in stateOptions" :key="item.id" :label="item.label" :value="item.value"/>
          </el-select>
        <el-date-picker v-model="query.startTime" type="date" placeholder="开始时间"  value-format="yyyy-MM-dd"></el-date-picker>
        <el-button size="medium"
                   type="primary" icon="el-icon-search" @click="handleFilter">查询
        </el-button>
<!--        <el-button size="medium"-->
<!--                   type="primary" icon="el-icon-search" @click="handleRefresh">更新血缘-->
<!--        </el-button>-->
      </div>
    </div>
    <!--由listLoading决定是否加载-->
    <el-table stripe :data="connectorList" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" prop="code" label="编号" width="180">
        <template slot-scope="scope">
          <span style="color:red;" @click="handleUpdate(scope.row.code )">{{scope.row.code }}</span>
<!--          <el-button  size="mini" type="danger" icon="el-icon-edit" @click="handleUpdate(scope.row.id)"></el-button>-->
        </template>
      </el-table-column>
      <el-table-column align="center" prop="name" label="名称"></el-table-column>
      <el-table-column align="center" prop="projectName" label="工作流实例"></el-table-column>
      <el-table-column align="center" prop="userName" label="执行用户" width="150"></el-table-column>
      <el-table-column align="center" prop="taskType" label="节点类型" width="100"></el-table-column>
      <el-table-column align="center"  label="状态" width="150px">
        <template slot-scope="scope">
          {{stateOptions[scope.row.state]['label']}}
        </template>
      </el-table-column>
<!--      <el-table-column align="center" prop="startTime" label="开始时间" width="150px"></el-table-column>-->
      <el-table-column align="center" prop="endTime" label="结束时间" ></el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center;"
      layout="sizes, prev, pager, next, jumper, ->, total, slot"
      @current-change="fetchData"
      @size-change="changeSize"
    />
    <!--
      创建和编辑应用的页面
    -->
    <el-dialog :close-on-click-modal="false"  :visible.sync="dialogFormVisible" width="900px" >
      <el-tabs v-model="activeName" @tab-click="handleClick" >
        <el-tab-pane label="调度详情" name="first">
          <el-form  :model="dataForm" label-position="left" label-width="130px" style='width: 860px;'>
            <el-form-item label="工作流名称" prop="name">
              <el-input v-model="dataForm.name" style="width: 500px" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="任务详情">
              <el-input  type="textarea" :rows="5" v-model="dataForm.taskParams" style="width: 500px" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="失败重试次数">
              <el-input v-model="dataForm.failRetryTimes" style="width: 500px" :disabled="true" ></el-input>
            </el-form-item>
            <el-form-item label="失败重试间隔">
              <el-input v-model="dataForm.failRetryInterval" style="width: 500px" :disabled="true" ></el-input>
            </el-form-item>
            <el-form-item label="延时执行时间">
              <el-input v-model="dataForm.delayTime" style="width: 500px" :disabled="true" ></el-input>
            </el-form-item>
            <el-form-item label="超时标志">
              <el-input v-model="dataForm.timeoutFlag" style="width: 500px" :disabled="true" >
                <templat slot-scope="scope">
                  {{
                    scope.row.dataForm.timeoutFlag == 0
                      ? "关闭"
                      : scope.row.dataForm.timeoutFlag == 1
                        ? "打开": ""
                  }}</templat>
              </el-input>
            </el-form-item>
            <el-form-item label="超时通知策略">
              <el-input v-model="dataForm.timeoutNotifyStrategy" style="width: 500px" :disabled="true" ></el-input>
            </el-form-item>
            <el-form-item label="超时时长">
              <el-input v-model="dataForm.timeout" style="width: 500px" :disabled="true" ></el-input>
            </el-form-item>
            <el-form-item label="任务提交时间">
              <el-input v-model="dataForm.submitTime" style="width: 500px" :disabled="true" ></el-input>
            </el-form-item>
            <el-form-item label="预期完成时间">
              <el-input v-model="dataForm.startTime" style="width: 500px" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="结束时间">
              <el-input v-model="dataForm.endTime" style="width: 500px" :disabled="true" ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
          </div>
        </el-tab-pane>
<!--        <el-tab-pane label="血缘关系" name="second">-->
<!--          <div id="categoryChart" style="width: 800px; height: 500px" />-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="表详情" name="third">-->
<!--          <el-descriptions class="margin-top" style="width:100%;" :column="1"  border >-->
<!--            <el-descriptions-item v-for="(val,item,index) in resultList" >-->
<!--              <template slot="label" :width="item.width">-->
<!--                {{item}}-->
<!--              </template>-->
<!--              {{val}}-->
<!--            </el-descriptions-item>-->
<!--          </el-descriptions>-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="角色管理" name="third">角色管理</el-tab-pane>-->
<!--        <el-tab-pane label="定时任务补偿" name="fourth">定时任务补偿</el-tab-pane>-->
      </el-tabs>

    </el-dialog>
  </div>
</template>

<script>

import api from '@/api/schedule/schedule'
import * as echarts from 'echarts';
import lineage from '@/api/assets/lineage'
import { Message } from 'element-ui';
import governApi from '@/api/govern/govern'

const stateOptions = [
  {id: 1, label: '提交成功', value: "0"},
  {id: 2, label: '正在运行', value: "1"},
  {id: 3, label: '准备暂停', value: "2"},
  {id: 4, label: '暂停', value: "3"},
  {id: 5, label: '准备停止', value: "4"},
  {id: 6, label: '停止', value: "5"},
  {id: 7, label: '失败', value: "6"},
  {id: 8, label: '成功', value: "7"},
  {id: 9, label: '需要容错', value: "8"},
  {id: 10, label: '终止', value: "9"},
  {id: 11, label: '等待线程', value: "10"},
  {id: 12, label: '等待依赖关系完成', value: "11"},
  {id: 13, label: '', value: "12"}

]

export default {
  data() {
    return {
      dialogFormVisible: false,
      activeName: 'first',
      dialogStatus: '',
      updateStatus:'',
      stateOptions,
      dataForm: {
        name:'',
        taskParams:'',
        submitTime:'',
        startTime:'',
        endTime:'',
        tableName:'',
        failRetryTimes:0,
        failRetryInterval:0,
        timeoutFlag:0,
        timeoutNotifyStrategy:0,
        timeout:0
      },
      query: {
        name:null,
        state:-1,
        startTime:'',
        userName:'',
        userId:0,

      },
      connectorList:[],
      cdata: [],
      link:[],
      resultList: [],
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
    }
  },

  created() {
    this.fetchData()

  },
  // mounted() {
  //
  // },
  methods: {
    // 加载banner列表数据
    init() {
      this.setChartData()
    },
    // 当页码发生改变的时候
    changeSize(size) {
      console.log(size)
      this.limit = size
      this.fetchData(1)
    },

    // 加载banner列表数据
    fetchData(page = 1) {
      console.log('翻页。。。' + page)
      // 异步获取远程数据（ajax）
      this.page = page
      /**
       * 获取所有调度
       */
      api.getScheduleList(this.query,this.page,this.limit).then(response => {
        // console.log("-----" + this.query.startDate)
        this.listLoading = true
        this.connectorList  = response.data.records
        // console.log("========tableData"+this.tableData)
        this.total = response.data.total
        this.listLoading = false

      })
    },
    // //获得connector列表
    // getList() {
    //   api.getScheduleList(this.query).then(response => {
    //     this.connectorList = response ;
    //   })
    // },
    handleUpdate(code) {
      this.activeName = 'first'
      this.dateForm = this.getscheduleDetail(code)
      this.dialogFormVisible = true
      this.dialogStatus = 'update'
      //页面渲染完之后立即执行，目的是为了拿到dom元素
      this.$nextTick(()=>{
        this.init()

      })

    },
    handleFilter() {
      this.query.pageNo = 1;
      this.fetchData();
    },
    resetForm(formName) {
      this.$nextTick(()=>{
        this.$refs[formName].resetFields();
      })
    },
    //查询详情
    getscheduleDetail(code) {
      this.dialogFormVisible = true
      this.dialogStatus = ''
      api.getSchedelDetail(code).then(response => {
        this.dataForm=response.data
      })
    },

    // setChartData() {
    //   const option = {
    //     title: {
    //       text: "血缘关系",
    //       left: "left",
    //     },
    //     tooltip: {},
    //     animationDurationUpdate: 1500,
    //     animationEasingUpdate: 'quinticInOut',
    //     series: [
    //       {
    //         type: 'graph',
    //         layout: 'none',
    //         symbolSize: 50,
    //         roam: true,
    //         label: {
    //           show: true
    //         },
    //         edgeSymbol: ['circle', 'arrow'],
    //         edgeSymbolSize: [4, 10],
    //         edgeLabel: {
    //           fontSize: 20
    //         },
    //         data:this.cdata,
    //         links:this.link,
    //         lineStyle: {
    //           opacity: 0.9,
    //           width: 2,
    //           curveness: 0
    //         }
    //       }
    //    ]
    //   };
    //
    //   // 基于准备好的dom，初始化echarts实例
    //   var myChart = echarts.init(document.getElementById("categoryChart"));
    //   myChart.clear();
    //   // 使用刚指定的配置项和数据显示图表。
    //   myChart.setOption(option);
    // },
    // //页面大小改变时
    // handleSizeChange(val){
    //   this.query.pageNo = 1
    //   this.userTaskQuery.pageSize = val
    //   this.getList();
    // },
    // //当前页面改变时
    // handleCurrentChange(val){
    //   this.query.pageNo = val
    //   this.getList();
    //
    // },
    handleClick(tab, event) {
      console.log("---------"+tab.index)
      if(tab.index == 0 ){

      }else if (tab.index == 1){
        lineage.getLineage("gmall.ads_page_path").then(response => {
          this.cdata=response.data;
          this.link = response.link;
          this.setChartData();
        })
      }else if (tab.index == 2){
        governApi.getTableInformation(this.query.dbName,this.query.tableName).then(response => {
          this.resultList = response;
          console.log(this.resultList)
        })
      }
      console.log(tab, event);
    },
    getMaxLength (arr) {
      return arr.reduce((acc, item) => {
        if (item) {
          let calcLen = this.getTextWidth(item)
          if (acc < calcLen) {
            acc = calcLen
          }
        }
        return acc
      }, 0)
    },
    /**
     * 使用span标签包裹内容，然后计算span的宽度 width： px
     * @param valArr
     */
    getTextWidth(str) {
      let width = 0;
      let html = document.createElement('span');
      html.innerText = str;
      html.className = 'getTextWidth';
      document.querySelector('body').appendChild(html);
      width = document.querySelector('.getTextWidth').offsetWidth;
      document.querySelector('.getTextWidth').remove();
      return width;
    }
  },
  watch: {
    /**
     * 监控表格的数据data，自动设置表格宽度
     * @param valArr
     */
    resultList(valArr) {
      const _this = this
      this.tableheader = fields.map(function (value) {
        const arr = valArr.map(x => x[value.property])  // 获取每一列的所有数据
        arr.push(value.label)  // 把每列的表头也加进去算
        value.width = _this.getMaxLength(arr) + 20 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
        return value
      })
    }
  }

}

</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-button--mini, .el-button--mini.is-round{padding:7px 6px}
</style>
